import React, { useContext, useRef } from "react";
import update from "immutability-helper";

import { LowCodeDesignerContext  } from "./Provider";
import DesignToolbar from "./Toolbar";
import useDesignActions from "./useActions";
import { DropTargetMonitor, useDrag, useDrop } from "react-dnd";
import { LowCodeContext } from "../core/Provider";
const style = {
  border: "1px dashed gray",
  padding: "0.8rem",
  // marginBottom: '.5rem',
  // backgroundColor: 'white',
  cursor: "move",
};
function selectBackgroundColor(isActive: boolean, canDrop: boolean) {
  // if (isActive) {
  //   return 'darkgreen'
  // } else if (canDrop) {
  //   return '#fff'
  // } else {
  //   return '#222'
  // }
  // return "#fff";
  // return canDrop?'red':'yellow'
}

const DesignFrame = ({ parentSchema, sortable, index, children, item }:any) => {
  return <div style={{border:'1px solid red',minHeight:10}}>{children}</div>
  const { updateDesign } = useDesignActions();
  const ref = useRef<HTMLDivElement>(null);

  const { setCurrentDesign, onDrop, currentDesign } = useContext(LowCodeDesignerContext);
  const { items } = useContext(QuickContext);

  const [{ isOver, canDrop }, drop] = useDrop(
    () => ({
      accept: "BOX",
      hover(_item: any, monitor) {
        if (!ref.current) {
          return;
        }
        setCurrentDesign({});

        // // // 拖动的索引
        const dragIndex = _item.$index;
        // //   // 放到
        const hoverIndex = index;
        const _items = items.properties["x-component-props"]["items"];
        console.log("item", item.index, JSON.stringify(item));
        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
          return;
        }
        // Determine rectangle on screen
        const hoverBoundingRect = ref.current?.getBoundingClientRect();

        // Get vertical middle
        const hoverMiddleY =
          (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

        // Determine mouse position
        const clientOffset = monitor.getClientOffset();

        // Get pixels to the top
        const hoverClientY = (clientOffset as any).y - hoverBoundingRect.top;

        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%

        // Dragging downwards
        if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
          return;
        }

        // Dragging upwards
        if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
          return;
        }

        // Time to actually perform the action
        // moveCard(dragIndex, hoverIndex)
        // console.log('component=',{dragIndex,hoverIndex})
        items.properties["x-component-props"]["items"] = update(_items, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, _items[dragIndex] as any],
          ],
        });
        // console.log('component=',{dragIndex,hoverIndex,_items},items.properties['x-component-props'])

        updateDesign();
        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        _item.$index = hoverIndex;
      },
      collect: (monitor: DropTargetMonitor) => ({
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
      }),
    }),
    [onDrop, item, items, parentSchema]
  );
  const [{ isDragging }, drag] = useDrag(
    {
      type: "BOX",
      item: () => {
        item.$index = index;
        return item;
      },
      collect: (monitor: any) => ({
        isDragging: monitor.isDragging(),
      }),
    },
    [item]
  );

  // const style: React.CSSProperties = {
  //   // transform: CSS.Transform.toString(transform),
  //   transform: `translate3d(${transform?.x || 0}px, ${transform?.y || 0}px, 0)`,
  //   // border: isDragging ? '1px dashed  red' : '1px dashed  #36cfc9',
  //   // margin: 5,
  //   // backgroundColor:isOver&&!isDragging&&item.isContainer?'red':'',
  //   // position:'absolute',
  //   // width:'100%',
  //   // zIndex:isDragging?9900:98,
  //   transition,
  // };
  const isActive = canDrop && isOver;

  const backgroundColor = selectBackgroundColor(isActive, isOver);

  if (item.isPageContainer) {
    return (
      <div
        data-id={item._id}
        // className="page-container-descrator"
        style={{ ...style, position: "relative" }}
        className={
          currentDesign._id == item._id ? "page-container-descrator-active" : ""
        }
        onClick={(e) => {
          setCurrentDesign(item);
          e.preventDefault();
          e.stopPropagation();
          updateDesign();
        }}
      >
        {currentDesign._id == item._id ? (
          <DesignToolbar disabledActions />
        ) : null}
        {children}
      </div>
    );
  }
  const opacity = isDragging ? 0 : 1;
  drag(drop(ref));
  return (
    <div
      ref={sortable ? ref : null}
      onClick={(e) => {
        setCurrentDesign(item);
        updateDesign();
        e.stopPropagation();
        e.preventDefault();
      }}
      style={{ ...style, opacity, position: "relative" }}
      className={
        currentDesign._id == item._id ? "design-container-descrator-active" : ""
      }
      // className={
      //   currentDesign._id == item._id
      //     ? "deigin-item deigin-item-active"
      //     : "deigin-item"
      // }
      // ref={setNodeRef}
      // {...listeners}
      // onMouseDown={(e) => {
      //   setCurrentDesign(item);
      //   updateDesign();
      //   e.stopPropagation();
      //   listeners?.onMouseDown(e);
      // }}
      // style={style}
    >
      {currentDesign._id == item._id ? <DesignToolbar item={item} /> : null}

      {children}
    </div>
  );
};
export default DesignFrame;
